package WizardInstall;
/*
SWT/JFace in Action
GUI Design with Eclipse 3.0
Matthew Scarpino, Stephen Holder, Stanford Ng, and Laurent Mihalkovic

ISBN: 1932394273

Publisher: Manning
 */


import java.io.File;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.util.ArrayList;
import org.eclipse.jface.wizard.IWizardPage;
import org.eclipse.jface.wizard.Wizard;
import XML.ConfigHelper;



/**
 * Manager of all the installation client
 * @author Guy & Liel
 *
 */
class ProjectWizard extends Wizard {

	private static final int PORT=8880;
	private static final String LOCALHOST="localhost";
	static public final String driver = "com.mysql.jdbc.Driver";
	static public final String connection ="jdbc:mysql://"+LOCALHOST+"/serverDatabase";
	
	/**
	 * Constructor to Project Wizard
	 */
	public ProjectWizard() {
		super();
	}
	/**
	 * check if the client in the summry page
	 */
	public boolean canFinish()
	{
		if(getContainer().getCurrentPage()==getSummaryPage())
		{
			return true;
		}
		return false;
	
	}
	/**
	 * Add pages to the installation
	 */
	public void addPages() 
	{
		addPage(new UserExistPage());
		addPage(new LoginPage());
		addPage(new RegisterPage());
		addPage(new ChooseDirectoryPage());
		addPage(new LoginDBPage());
		addPage(new SummaryPage());
	}
	/**
	 * Finish install
	 */
	public boolean performFinish() 
	{
		//TODO: Add every thing to the DB
		UserExistPage dirPage = getUserExistPage();
		if (!dirPage.accountExist()) 
		{
			String userName=getRegisterPage().getUserName();
			String passward=getRegisterPage().getPassword();
			String email=getRegisterPage().getTextEmail();
			String mainFolder=getChoosePage().getDirectory();
			String dbUserName=getLoginDDPage().getUserName();
			String dbPassword=getLoginDDPage().getPassword();
			
			try 
			{
				ConfigHelper.writeXML(dbUserName, dbPassword);
				ConfigHelper.writeXmlClient(userName, passward, email, mainFolder);
			}
			catch (Exception e1) 
			{
				// TODO Auto-generated catch block
				e1.printStackTrace();
			}
			
			try 
			{
				Class.forName(driver).newInstance();
				Connection con =DriverManager.getConnection(connection, dbUserName, dbPassword);

				System.out.println("Jdbc Mysql Connection String :");
				System.out.println(connection);

				System.out.println("User Name :" + dbUserName);
				System.out.println("Password :" + dbPassword);

				java.sql.Statement csStatement=con.createStatement();
				String strSQL="INSERT INTO tbl_users(user_name, password, email) VALUES('"+userName+"','"+passward+"','"+email+"')";
				System.out.println(strSQL);
				csStatement.execute(strSQL);
			}
			catch (InstantiationException e) 
			{
				// TODO Auto-generated catch block
				e.printStackTrace();
			} 
			catch (IllegalAccessException e) 
			{
				// TODO Auto-generated catch block
				e.printStackTrace();
			} 
			catch (ClassNotFoundException e) 
			{
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (SQLException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			
			
			
			
			System.out.println("Use not exist");
			ChooseDirectoryPage choosePage = getChoosePage();
			System.out.println("Using directory: " + choosePage.getDirectory());
		}
		return true;
	}


	private ChooseDirectoryPage getChoosePage() {
		return (ChooseDirectoryPage) getPage(ChooseDirectoryPage.PAGE_NAME);
	}
	private LoginDBPage getLoginDDPage()
	{
		return (LoginDBPage)getPage(LoginDBPage.PAGE_NAME);
	}
	private SummaryPage getSummaryPage() {
		return (SummaryPage) getPage(SummaryPage.PAGE_NAME);
	}

	private LoginPage getLoginPage() {
		return (LoginPage) getPage(LoginPage.PAGE_NAME);
	}
	private RegisterPage getRegisterPage()
	{
		return (RegisterPage)getPage(RegisterPage.PAGE_NAME);
	}
	private UserExistPage getUserExistPage()
	{
		return (UserExistPage)getPage(UserExistPage.PAGE_NAME);
	}
	
	public boolean performCancel() {
		System.out.println("Perform Cancel called");
		return true;
	}
	/**
	 * Get the next page
	 */
	public IWizardPage getNextPage(IWizardPage page) 
	{
		//Asking if User Exist
		if (page instanceof UserExistPage) 
		{
			UserExistPage dirPage = (UserExistPage) page;
			if(dirPage.accountExist() && dirPage.accountNotExist())
			{
				UserExistPage userExistPage=(UserExistPage)getPage(UserExistPage.PAGE_NAME);
				userExistPage.updateLabelError("Select only one option");
				return userExistPage;
			}
			if(!dirPage.accountExist() && !dirPage.accountNotExist())
			{
				UserExistPage userExistPage=(UserExistPage)getPage(UserExistPage.PAGE_NAME);
				userExistPage.updateLabelError("You have to select one of the option");
				return userExistPage;
			}
			if (dirPage.accountExist()) //User Exist
			{
				LoginPage loginPage=(LoginPage) getPage(LoginPage.PAGE_NAME);
				return loginPage;
			}
			if(dirPage.accountNotExist())//USer not exist
			{
				RegisterPage registerPage=(RegisterPage) getPage(RegisterPage.PAGE_NAME);
				return registerPage;
			}
		
		}
		IWizardPage nextPage = super.getNextPage(page);
		//Check User Exist

		if(page instanceof LoginPage)
		{			
			try 
			{
				//URL user name add
				String strURL="http://"+LOCALHOST+":"+PORT+"/LoginServlet?userName="+getLoginPage().getUserName();
				//URL password add
				strURL+="&password="+getLoginPage().getPassword();
				//Create URL
				URL loginServlet = new URL(strURL);
				URLConnection servletConnection = loginServlet.openConnection();
				servletConnection.setAllowUserInteraction(true);
				//reading back data from servlet
				ObjectInputStream inputFromServlet = new ObjectInputStream(servletConnection.getInputStream());
				@SuppressWarnings("unchecked")
				ArrayList<String> resultantData = (ArrayList<String>) inputFromServlet.readObject();
				if(!resultantData.isEmpty())
				{
					LoginPage loginPage=(LoginPage) getPage(LoginPage.PAGE_NAME);
					getLoginPage().updateTextError(resultantData.get(0).toString());
					return loginPage;
				}
				else
				{
					SummaryPage summaryPage=(SummaryPage) getPage(SummaryPage.PAGE_NAME);
					String str="You had already been installed Clever DropBox";
					summaryPage.updateText(str);

					return summaryPage;
				}

			} 
			catch (MalformedURLException e1)
			{
				e1.printStackTrace();
			} 
			catch (IOException e) 
			{
				e.printStackTrace();
			}
			catch (ClassNotFoundException e) 
			{
				e.printStackTrace();
			}
		}
		//Check Registration
		if(page instanceof RegisterPage)
		{
			String strAllError="";
			getRegisterPage().updateTextError(strAllError);

			try 
			{
				//URL user name add
				String strURL="http://"+LOCALHOST+":"+PORT+"/RegisterServlet?userName="+getRegisterPage().getUserName();
				//URL password add
				strURL+="&password="+getRegisterPage().getPassword();
				//URL re-password add
				strURL+="&rePassword="+getRegisterPage().getTextRepassword();
				//URL email
				strURL+="&email="+getRegisterPage().getTextEmail();
				//Create URL
				URL registerServlet = new URL(strURL);
				URLConnection servletConnection = registerServlet.openConnection();
				servletConnection.setAllowUserInteraction(true);
				//reading back data from servlet
				ObjectInputStream inputFromServlet = new ObjectInputStream(servletConnection.getInputStream());
				@SuppressWarnings("unchecked")
				ArrayList<String> resultantData = (ArrayList<String>) inputFromServlet.readObject();
				if(resultantData.isEmpty())
				{
					ChooseDirectoryPage chooseDirectoryPage=(ChooseDirectoryPage) getPage(ChooseDirectoryPage.PAGE_NAME);
					return chooseDirectoryPage;
				}
				else
				{
					RegisterPage registerPage=(RegisterPage) getPage(RegisterPage.PAGE_NAME);
					for(int i=0; i<resultantData.size(); i++)
					{
						strAllError+= resultantData.get(i).toString();
					
					}
					getRegisterPage().updateTextError(strAllError);
					return registerPage;

				}

			} 
			catch (MalformedURLException e1)
			{
				e1.printStackTrace();
			} 
			catch (IOException e) 
			{
				e.printStackTrace();
			}
			catch (ClassNotFoundException e) 
			{
				e.printStackTrace();
			} 

		}
		if(page instanceof ChooseDirectoryPage)
		{
			String strFolder=getChoosePage().getDirectory().toString();
			if(strFolder!="")
			{
				File file=new File(strFolder.toString());
				boolean exists = file.exists();
				if (exists) 
				{
					LoginDBPage loginDBPage=(LoginDBPage) getPage(LoginDBPage.PAGE_NAME);
					return loginDBPage;
				}
			}
			ChooseDirectoryPage chooseDirectoryPage=(ChooseDirectoryPage) getPage(ChooseDirectoryPage.PAGE_NAME);
			chooseDirectoryPage.updateTextError("Folder dosen't Exist,please select folder");
			return chooseDirectoryPage;
		}
		if(page instanceof LoginDBPage)
		{
			SummaryPage summaryPage=(SummaryPage) getPage(SummaryPage.PAGE_NAME);
			String str="Thank you for installing Clever DropBox \n\n";
			str+="Your details are:\n\n";
			if(getLoginPage().getUserName().isEmpty())
			{
				str+="User Name:"+getRegisterPage().getUserName().toString()+"\n";
			}
			else
			{
				str+="User Name:"+getLoginPage().getUserName().toString()+"\n";
			}
			str+="Password:*******\n";			
			summaryPage.updateText(str);

			return summaryPage;
		}
		return nextPage;
	}
}